import { login, logout, auth } from '@/api/system/auth'
import { getToken, setToken, removeToken } from '@/utils/cookies'
// import router, { resetRouter } from '@/router'
import router from '@/router'
import { encrypt } from '@/utils/keygen'

const getPath = (root, path) => {
  const result = []
  if (root.children && root.children.length > 0) {
    for (const child of root.children) {
      result.push([path, child.path].join('/'))
      getPath(child)
    }
  }
  return result
}

const state = {
  token: getToken(),
  loginName: '',
  name: '',
  avatar: '',
  isAdmin: false,
  roles: [],
  hasInfo: false,
  loginPath: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_LOGIN_NAME: (state, loginName) => {
    state.loginName = loginName
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_IS_ADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_HAS_INFO: (state, hasInfo) => {
    state.hasInfo = hasInfo
  },
  SET_LOGIN_PATH: (state, loginPath) => {
    state.loginPath = loginPath
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: username.trim(), password: encrypt(password) }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      auth(state.loginName).then(response => {
        const { data } = response
        commit('SET_LOGIN_NAME', data.loginName)
        commit('SET_NAME', data.userName)
        commit('SET_AVATAR', data.avatarFile)
        let userRoles = []
        if (data.adminFlg === '1') {
          userRoles = ['admin']
        } else {
          userRoles = data.roles === undefined ? [] : data.roles
        }
        commit('SET_IS_ADMIN', data.adminFlg === '1')
        commit('SET_ROLES', userRoles)
        commit('SET_HAS_INFO', true)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_LOGIN_NAME', '')
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_IS_ADMIN', false)
      commit('SET_HAS_INFO', false)
      commit('SET_LOGIN_PATH', '')
      removeToken()
      // resetRouter()
      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

  setAvatar({ commit }, avatar) {
    return new Promise((resolve, reject) => {
      commit('SET_AVATAR', avatar)
      resolve()
    })
  },

  setLoginPath({ commit }, path) {
    return new Promise((resolve, reject) => {
      commit('SET_LOGIN_PATH', path)
      resolve()
    })
  },

  redirect({ commit }, accessRoutes) {
    return new Promise((resolve, reject) => {
      const whitePath = ['', '/dashboard', '/profile/index']
      if (state.loginPath !== '/' && !whitePath.includes(state.loginPath)) {
        let loginPathArr = state.loginPath.split('/')
        loginPathArr = loginPathArr.filter((item) => {
          return item !== ''
        })
        let isExisted = false
        let root = null
        for (const route of accessRoutes) {
          if (route.path.replace('/', '') === loginPathArr[0]) {
            root = route
            break
          }
        }
        if (root) {
          const allPath = getPath(root, root.path)
          isExisted = allPath.includes(state.loginPath)
        }
        if (isExisted === false) {
          setTimeout(() => {
            try {
              router.push({ path: '/', query: {}})
            } catch (err) {
              console.log(err)
            }
          }, 0)
        }
      }
      resolve()
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  changeToken({ commit }, token) {
    return new Promise(resolve => {
      commit('SET_TOKEN', token)
      setToken(token)
      resolve()
    })
  },

  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token'

  //   commit('SET_TOKEN', token)
  //   setToken(token)
  //   const { roles } = await dispatch('getInfo')
  //   // resetRouter()
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   if (accessRoutes.length > 0) {
  //     for (const r of accessRoutes) {
  //       router.addRoute(r)
  //     }
  //   }
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
